package com.jhws.core.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.util.LogHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;

public class tempUserFilter extends UserFilter{

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if(super.isAccessAllowed(request, response, mappedValue))
		    return true;
		Session s = getSubject(request,response).getSession();

		if(s != null && s.getAttribute(TblUserDimBo.USER_INFO_REFERENCE) != null) {
			LogHelper.d("get redis session isAccessAllowed");
			return true;
		}

        return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		/* 判断当前请求是否需要json返回(ajax请求), 返回json重定向数据，让前端自动跳转 */

		if(request.getServerPort() == 80) {
			String accept = WebUtils.toHttp(request).getHeader("Accept");
			if(StringUtils.isNotEmpty(accept) && accept.contains("json")){
				response.setContentType(MediaType.APPLICATION_JSON_VALUE);
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write("{\"ret_code\":-1,\"status\":302,\"location\":\""+getLoginUrl()+"\"}");
				return false;
			}
			return super.onAccessDenied(request, response);
		}
		else
			return true;
	}

}
